package com.example.aircraftwar2024.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.aircraftwar2024.ActivityManager;
import com.example.aircraftwar2024.R;
import com.example.aircraftwar2024.game.BaseGame;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RecordActivity extends AppCompatActivity {


    String fileName = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);

        //设置难度显示
        TextView textView = findViewById(R.id.textView_gameMode);
        String gameMode = OfflineActivity.gameMode; // 将你的变量设置为你想要显示的动态内容
        textView.setText(gameMode);


        //获得Layout里面的ListView
        ListView list = (ListView) findViewById(R.id.listView);

        //生成适配器的Item和动态数组对应的元素
        SimpleAdapter listItemAdapter = null;
        try {
            listItemAdapter = new SimpleAdapter(
                    this,
                    getData(),
                    R.layout.activity_record_item,
                    new String[]{"rank","userName","score","time"},
                    new int[]{R.id.rank,R.id.userName,R.id.score,R.id.time}
            );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //添加并且显示
        list.setAdapter(listItemAdapter);


        //添加单击监听
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                //获取单击位置的Map
                Map<String, Object> chosenUser = (Map<String, Object>) arg0.getItemAtPosition(arg2);

                // 创建AlertDialog.Builder对象
                AlertDialog.Builder builder = new AlertDialog.Builder(RecordActivity.this);
                builder.setTitle("提示");
                builder.setMessage("确定要删除这项记录吗？");
                // 设置对话框按钮
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 点击“确定”按钮时的操作
                        System.out.println(chosenUser);
                        try {
                            deleteUser((Integer) chosenUser.get("rank"));
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 无操作
                    }
                });

                AlertDialog dialog = builder.create();
                dialog.show();

            }
        });

        Button btnReplay=(Button) findViewById(R.id.btnReplay);

        btnReplay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityManager activityManager= ActivityManager.getActivityManager();

                while (!(activityManager.currentActivity() instanceof MainActivity)){
                    activityManager.finishActivity(activityManager.currentActivity());
                }

                Activity target=activityManager.currentActivity();
                Intent intent = new Intent(RecordActivity.this, target.getClass());

                startActivity(intent);
            }
        });

    }


    private ArrayList<Map<String,Object>> getUserInfo() throws IOException {
        int gameMode=getIntent().getIntExtra("gameMode",0);

        switch (gameMode) {
            case 0:
                fileName="easy_userInfo.txt";
                break;
            case 1:
                fileName="medium_userInfo.txt";
                break;
            case 2:
                fileName="hard_userInfo.txt";
                break;
        }

        File file = new File(getFilesDir(), fileName);
        System.out.println(file.exists());

        if(!file.exists()){
            boolean created = file.createNewFile();
            if (!created) {
                throw new IOException("Failed to create file " + fileName);
            }
        }


        FileInputStream fis = openFileInput(fileName);
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader br = new BufferedReader(isr);

        ArrayList<Map<String,Object>> userInfo=new ArrayList<>();
        String user;
        while ((user = br.readLine()) != null) {
            System.out.println(user);
            userInfo.add(parseInfo(user));
        }
        br.close();
        isr.close();
        fis.close();

        return userInfo;
    }

    //正则表达式，解析读入行
    public Map<String, Object> parseInfo(String user){
        String[] data=user.split("\\|");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rank",data[0]);
        map.put("userName", data[1]);
        map.put("score", data[2]);
        map.put("time", data[3]);
        return map;
    }


    /**
     * 加入新用户信息并重新排序
     * @param userInfo
     * @param newUser
     */
    private void reRankUser(ArrayList<Map<String,Object>> userInfo, Map<String, Object> newUser){
        int addPosition = 0;
        for (Map<String,Object> user : userInfo) {
            int currentUserScore = Integer.parseInt((String) user.get("score"));
            int newScore = (int) newUser.get("score");
            if (newScore > currentUserScore) {
                break;
            }
            addPosition++; // 继续向后遍历
        }
        // 将新用户插入到适当的位置
        userInfo.add(addPosition, newUser);
        int rank=1;
        for (Map<String,Object> user : userInfo) {
            user.put("rank",rank);
            rank+=1;
        }
    }

    /**
     * 添加新用户
     * @param userInfo
     * @param newUser
     */
    private void addUser(ArrayList<Map<String,Object>> userInfo, Map<String, Object> newUser) {
        reRankUser(userInfo,newUser);
        writeBack(userInfo);
    }

    private List<Map<String, Object>> getData() throws IOException {

        Map<String, Object> newUser = new HashMap<String, Object>();
        newUser.put("userName", "test");
        newUser.put("score", BaseGame.score);
        newUser.put("time", new Date().toString());

        ArrayList<Map<String,Object>> userInfo=getUserInfo();
        addUser(userInfo,newUser);
        return userInfo;
    }

    private void deleteUser(int rank) throws IOException {
        ArrayList<Map<String,Object>> userInfo=this.getUserInfo();
        for(Map<String,Object> user:userInfo){
            String str= user.get("rank").toString();
            if (Integer.parseInt(str)==rank){
                userInfo.remove(user);
                break;
            }
        }

        rank=1;
        for (Map<String,Object> user : userInfo) {
            user.put("rank",rank);
            rank+=1;
        }
        writeBack(userInfo);

        //重载列表
        SimpleAdapter listItemAdapter = null;
        listItemAdapter = new SimpleAdapter(
                this,
                userInfo,
                R.layout.activity_record_item,
                new String[]{"rank","userName","score","time"},
                new int[]{R.id.rank,R.id.userName,R.id.score,R.id.time}
        );

        ListView list = (ListView) findViewById(R.id.listView);

        list.setAdapter(listItemAdapter);
    }

    /**
     * 写回文件
     * @param userInfo
     */
    private void writeBack(ArrayList<Map<String,Object>> userInfo){
        FileOutputStream fos= null;
        try {
            fos = openFileOutput(fileName,MODE_PRIVATE);
            OutputStreamWriter osw=new OutputStreamWriter(fos);
            BufferedWriter bw=new BufferedWriter(osw);
            for(Map<String, Object> user:userInfo){
                String str=user.get("rank")+"|"+user.get("userName")+"|"+ user.get("score") +"|"+user.get("time")+'\n';
                bw.write(str);
            }
            bw.close();
            osw.close();
            fos.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}